﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _79Ini文件读取类
{
    internal class IniFile
    {
        private Dictionary<string, Dictionary<string, string>> dic = new Dictionary<string, Dictionary<string, string>>();

        //读取文件把文件中的数据填充到字典中方便访问
        public void ReadFile(string iniFilePath)
        {
            string[] array = File.ReadAllLines(iniFilePath);
            string mainKey = "";
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].StartsWith(" ") || array[i].EndsWith(" "))
                {
                    array[i] = array[i].Trim();
                    if (array[i] == "") continue;
                }

                //看下是主键还是子键
                if (array[i].StartsWith("["))
                {
                    mainKey = array[i].Substring(1, array[i].Length - 2);
                    dic.Add(mainKey, new Dictionary<string, string>());
                }
                else if (array[i].Contains('='))
                {
                    string[] kv = array[i].Split('=');
                    dic[mainKey].Add(kv[0].TrimEnd(), kv[1].TrimStart());
                }
            }
        }

        public string GetString(string mainKey, string subKey)
        {
            return dic[mainKey][subKey];
        }

        public int GetInt(string mainKey, string subKey)
        {
            return int.Parse(GetString(mainKey, subKey));
        }

        public float GetFloat(string mainKey, string subKey)
        {
            return float.Parse(GetString(mainKey, subKey));
        }

        public DateTime GetDateTime(string mainKey, string subKey)
        {
            return DateTime.Parse(GetString(mainKey, subKey));
        }
    }
}